package com.rzgeo.rzmaplib.util;

import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.rzgeo.rzmaplib.R;

import java.util.List;

import static android.view.ViewGroup.FOCUS_AFTER_DESCENDANTS;
import static android.widget.AbsListView.CHOICE_MODE_NONE;
import static android.widget.AbsListView.TRANSCRIPT_MODE_DISABLED;

/**
 * Created by zhanghang on 2018/4/24.
 */
class RmlEditAttrsHelper {


    public static void EditAttrs(final Context context, RmlData.FeatureLayerData data, @NonNull final RmlUtil.Dialog.OnInputText onResult) {
        final ListView listView = new ListView(context);

        listView.setMinimumWidth(800);
        listView.setMinimumHeight(600);

        listView.setAdapter(new FeatureAdapter(context,data));
//        listView.setItemsCanFocus(false);
        listView.setChoiceMode(CHOICE_MODE_NONE);
        listView.setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);

        listView.setTranscriptMode(TRANSCRIPT_MODE_DISABLED);

        new AlertDialog.Builder(context).setTitle("设置文本")
                .setIcon(android.R.drawable.ic_menu_edit)
                .setCancelable(false)
                .setView(listView)
                .setPositiveButton("修改属性", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        RmlData.FeatureLayerData newFeature = ((FeatureAdapter) listView.getAdapter()).getData();

                        ListenableFuture<Void> ll = newFeature.layer.getFeatureTable().updateFeatureAsync(newFeature.feature);
                        newFeature.layer.getFeatureTable().addDoneLoadingListener(new Runnable() {
                            @Override
                            public void run() {
                                onResult.onResult("更新数据");
                            }
                        });
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onResult.onCancel();
                    }
                })
                .show().setCanceledOnTouchOutside(false);

    }

    private static class FeatureAdapter extends BaseAdapter{
        private final LayoutInflater _inflater;
        private final List<Field> _fields;
        private RmlData.FeatureLayerData _featureLayerData;

        public  FeatureAdapter(Context context,RmlData.FeatureLayerData featureLayerData){
            _inflater= LayoutInflater.from(context);
            _featureLayerData=featureLayerData;
            _fields=_featureLayerData.layer.getFeatureTable().getFields();
        }
        @Override
        public int getCount() {
            return _fields.size();
        }

        @Override
        public Object getItem(int position) {
            return _featureLayerData.feature.getAttributes().get(_fields.get(position).getName());
        }

        @Override
        public long getItemId(int position) {
                return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder4Attrs holder;
            if (convertView == null) {
                convertView = _inflater.inflate(R.layout.comp_feature_info_feature_attrs_editor, null);
                holder = new ViewHolder4Attrs(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder4Attrs) convertView.getTag();
            }

            Field fd = _fields.get(position);
            holder.setData(
                    _featureLayerData.feature.getAttributes().get(fd.getName()),
                    fd);
            return convertView;
        }

        public RmlData.FeatureLayerData getData() {
            return _featureLayerData;
        }
    }

    public static class ViewHolder4Attrs {

        private final TextView txvName;
        private final EditText tinValue;

        public ViewHolder4Attrs(View convertView) {
            txvName = convertView.findViewById(R.id.txv_field);
            tinValue = convertView.findViewById(R.id.tin_value);
            tinValue.setSingleLine();
        }

        public void setData(Object o, Field field) {
            if (RmlUtil.isValid(field.getAlias()))
                txvName.setText(field.getAlias());
            else
                txvName.setText(field.getName());


            boolean editable = false;
            Field.Type t = field.getFieldType();
            if (t == Field.Type.INTEGER || t == Field.Type.SHORT) {
                tinValue.setText(o == null ? "" : o.toString());
                tinValue.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
                editable = true;
            } else if (t == Field.Type.DOUBLE || t == Field.Type.FLOAT) {
                tinValue.setText(o == null ? "" : o.toString());
                tinValue.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                editable = true;
            } else if (t == Field.Type.DATE) {
                tinValue.setText(RmlUtil.Convert.toDateString(o));
                tinValue.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE);
                editable = true;
            } else if (t == Field.Type.TEXT) {
                tinValue.setText(o == null ? "" : (String) o);
                tinValue.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                editable = true;
            } else if (t == Field.Type.GLOBALID || t == Field.Type.GUID || t == Field.Type.OID) {
                tinValue.setText(o == null ? "" : o.toString());
                tinValue.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                editable = false;
            } else {
                tinValue.setText("不支持查看");
                editable = false;
            }

            if (editable) {
//                tinValue.setFocusableInTouchMode(true);
//                tinValue.setFocusable(true);
                tinValue.setEnabled(true);

//                tinValue.requestFocus();
            } else {
//                tinValue.setFocusable(false);
//                tinValue.setFocusableInTouchMode(false);
                tinValue.setEnabled(false);
            }
        }
    }
}
